const base = "https://movie.douban.com/subject/"
const doubanID = "26739551/"
const video = "https://movie.douban.com/trailer/219491"

const puppeteer = require("puppeteer")

const sleep = time => new Promise(resolve => {
    setTimeout(resolve(1), time)
})


; (async () => {
    console.log('start visit the target page')
    const brower = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false
    })

    const page = await brower.newPage()

    await page.goto(base+doubanID, {
        waitUntil: 'networkidle2'
    })
    // console.log(2)
    await sleep(1000)
  
    const result = await page.evaluate(() => {
        var $ = window.$
        var it =  $(".related-pic-video")
        if (it && it.length>0){
            var link = it.attr('href')
            var cover = it.attr("style")
            // (http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
            cover =  cover.match( /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/)
            cover = cover[0]
        }
        return {
            link,
            cover
        }
    })

    let video
    if(result.link){
        await page.goto(result.link,{
            waitUntil:'networkidle2'
        })
        await sleep(2000)

        video = await page.evaluate(()=>{
            var $ =window.$
            var it = $("source")
            if (it && it.length>0){
                return it.attr('src')
            }else{
                return ""
            }
        })
    }

    const data={
        video,
        doubanID,
        cover:result.cover
    }

    brower.close()
    console.log(result)
    console.log("end")
    process.send({data})
    process.exit(0)
})()

